<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <div class="formTitle-root">
      <div class="form-title-p">下发计划信息</div>
    </div>

    <VForm
      ref="vformComponents1"
      :form="formData1.form"
      :options="formData1.options"
      :rules="formData1.rules"
      :labelWidth="formData1.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <span slot="footer" class="dialog-footer">
     <el-button @click="cancel">{{openType!='detail' ? '取 消':'返 回'}}</el-button>
     <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    patrolPlanDistributeDetail,
    patrolPlanDistributeUpdate,
    patrolPlanDistributeAdd,
    patrolModelList
  } from '@/api/risk/patrol'
  import {
    getInstitutionList
  } from '@/api/system/institution'
  import {
    getDeptList,getUserList
  } from '@/api/risk/dept'
  import { treeDataChild } from '@/api/risk/treeData'
  import VForm from "@/components/VForm/index";
  import { collectBuildingProjectList } from '@/api/build/project'
  export default {
    components: {
      VForm,
    },
    props: {
      width: {
        type: String,
        default: "80%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id:{},
      openType:{
        type:String,
        default:"add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      bClassifyOptions:{},
      planTypeOptions:{},
      curPlanId:{}
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          let w = this.width.split('%')[0]
          if(w>=60){
            this.rowspan = 2
          }else{
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'bClassifyOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiLargeType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'planTypeOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='planType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'planCycleOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='planCycle'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptionsForm':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiSmallType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'modelList':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='modelId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'formData.form.busiLargeType':{
        handler(newVal, oldVal) {
          this.watchChangeLargeType()
        },
        deep: true,
        immediate: true
      },
      'formData.form.busiSmallType':{
        handler(newVal, oldVal) {
          if(newVal) {
            this.watchChangeSmallType()
          }
        },
        deep: true,
        immediate: true
      },
      'belongUnitIdList':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='execUnitId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'openType':{
        handler(newVal, oldVal) {
          // 判断是否详情，添加不可编辑标识
          this.formData.options.forEach(t=>{
            t.disabled = newVal=='detail' ? true : false
            if(newVal!='detail'){
              t.disabled = this.noBlank(this.curPlanId) ? true : false
            }
          })
          this.formData1.options.forEach(t=>{
            t.disabled = newVal=='detail' ? true : false
          })
        },
        deep: true,
        immediate: true
      },
      'belongStreetUnitIdList':{
        handler(newVal, oldVal) {
          this.formData1.options.forEach(t=>{
            if(t.key=='execStreetUnitId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'formData.form.execUnitId':{
        handler(newVal, oldVal) {
          if(newVal){
            // 重新查询单位、街道信息
            this.getUnitListData(newVal)
            this.getStreetUnitListData(newVal);
          }
        },
        deep: true,
        immediate: true
      },
      'buildingOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'buildingId') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        rowspan:1,
        dict:{},
        formData1:{
          form: {
            execStreetUnitId:[],
            execStreetUnit:"",
            execRequire:"",
          },
          options: [
            // {
            //   title: "街道执行单位",
            //   key: "execStreetUnitId",
            //   type: "select",
            //   multiple:true,
            //   option: {
            //     data: this.belongStreetUnitIdList,
            //     props: {
            //       key: "id", // 指定key对应data的字段
            //       label: "name", // 指定label对应data的字段
            //       value: "id", // 指定value对应data的字段
            //     },
            //   },
            //   // 添加默认值，防止更新不及时
            //   disabled:false
            // },
            {
              title: "执行要求",
              key: "execRequire",
              type: "textarea",
              columnWidth: 'w100max',
              disabled:false
            },
          ],
          rules:{
            execStreetUnitId :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            execRequire :[
              {max:256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
          },
          labelWidth: "140px",
        },
        formData: {
          form: {
            id:"",
            planName:"",
            busiLargeType:"",
            busiSmallType:"",
            modelId:"",
            planType:"",
            planCycle:"",
            execUnitId:"",
            execUnit:"",
            planStartDate:"",
            planEndDate:"",
            remark:"",
            buildingId: "",
          },
          options: [

            {
              title: "所属工地",
              key: "buildingId",
              type: "select",
              multiple: false,
              option: {
                data: this.buildingOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "projectName", // 指定label对应data的字段
                  value: "id", //指定value对应data的字段
                }
              }
            },

            {
              title: "计划名称",
              key: "planName",
              type: "text",
            },
            {
              title: "业务专题大类",
              key: "busiLargeType",
              type: "select",
              multiple:false,
              event: 'changeLargeType',
              option: {
                data: this.bClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },
            {
              title: "业务专题细类",
              key: "busiSmallType",
              type: "select",
              multiple:false,
              event: 'changeSmallType',
              option: {
                data: this.sClassifyOptionsForm,
                props: {
                  key: "code", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "code", // 指定value对应data的字段
                },
              },
            },
            {
              title: "巡查表单",
              key: "modelId",
              type: "select",
              multiple:false,
              option: {
                data: this.modelList,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "modelName", // 指定label对应data的字段
                  value: "id", // 指定value对应data的字段
                },
              },
            },
            {
              title: "计划巡检类型",
              key: "planType",
              type: "select",
              multiple:false,
              option: {
                data: this.planTypeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "计划周期",
              key: "planCycle",
              type: "select",
              multiple:false,
              option: {
                data: this.planCycleOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "执行单位",
              key: "execUnitId",
              type: "select",
              multiple:false,
              option: {
                data: this.belongUnitIdList,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "name", // 指定label对应data的字段
                  value: "id", // 指定value对应data的字段
                },
              },
            },
            {
              title: "计划开始日期",
              key: "planStartDate",
              type: "date",
            },
            {
              title: "计划结束日期",
              key: "planEndDate",
              type: "date",
            },
            {
              title: "计划描述",
              key: "remark",
              type: "textarea",
              columnWidth: 'w100max',
            },
          ],
          rules: {
            planName :[
              { required: true, message: '请输入', trigger: 'blur' },
              {max:64, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            planType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            modelId :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            busiLargeType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            busiSmallType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            // planCycle :[
            //   { required: this.getRequire(), message: '请选择', trigger: 'change' },
            // ],
            execUnitId :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            planStartDate :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            planEndDate :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            remark :[
              {max:256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
          },
          labelWidth: "140px",
        },
        // 字典
        sClassifyOptionsForm:[],
        planCycleOptions:[],
        modelList:[],
        belongUnitIdList:[],
        belongStreetUnitIdList:[],
        buildingOptions: [],
      };
    },
    methods: {
      noBlank(val) {
        if (val != "" && val != null && val != undefined) {
          return true;
        }
        return false;
      },
      toLoadMethods(methods) {
        this[methods]()
      },
      watchChangeSmallType(){
        let disableFlag = this.openType=='detail' ? 1 : 0
        let delFlag =  this.openType=='detail' ? 1 : 0
         let data = {
           busiLargeType:this.formData.form.busiLargeType,
           busiSmallType:this.formData.form.busiSmallType,
           disableFlag:disableFlag,
           delFlag:delFlag
         }
         patrolModelList(data).then(res=>{
           if(res.code==200){
             this.modelList = res.data
           }
         })
      },
      watchChangeLargeType(){
        let queryData ={}
        queryData.name='hazardBClassify';
        queryData.code =this.formData.form.busiLargeType
        treeDataChild(queryData).then(res=>{
          if(res.code==200) {
            this.sClassifyOptionsForm = res.data
          }
        })
      },
      changeLargeType(){
        this.formData.form.busiSmallType = ''
      },
      changeSmallType(){
          this.formData.form.modelId = ''
      },
      initData(){
          this.formData.form.id = "",
          this.formData.form.planName = "",
          this.formData.form.busiLargeType = "",
          this.formData.form.busiSmallType = "",
          this.formData.form.modelId = "",
          this.formData.form.planType = "",
          this.formData.form.planCycle = "",
          this.formData.form.execUnitId = "",
          this.formData.form.execUnit = "",
          this.formData.form.planStartDate = "",
          this.formData.form.planEndDate = "",
          this.formData.form.remark = "",
          this.formData1.form.execStreetUnitId = [],
          this.formData1.form.execStreetUnit = "",
          this.formData1.form.execRequire = "",
          this.modelList= []
          this.sClassifyOptionsForm = []
          this.belongUnitIdList = []
          this.belongStreetUnitIdList = []
      },
      sure(){
        console.log('sure===',this.formData.form)
        this.$refs.vformComponents.$refs.form.validate().then(res=>{
          if(this.formData.form.planType==1 && !this.noBlank(this.formData.form.planCycle)){
            this.$message.warning("计划型巡查计划需选择计划周期")
            return
          }
          // 校验分派信息
          this.$refs.vformComponents1.$refs.form.validate().then(res=>{
            // 执行单位
            let item = this.belongUnitIdList.find(x=>x.id == this.formData.form.execUnitId)
            if(undefined!=item){
              this.formData.form.execUnit = item.name
            }
            // 执行街道
            let streetNameTemp = []
            this.formData1.form.execStreetUnitId.forEach(t=>{
               let streetItem = this.belongStreetUnitIdList.find(x=>x.id == t)
               if(undefined != streetItem){
                  streetNameTemp.push(streetItem.name)
               }
            })
            let tempParam = {
              ...this.formData.form,
              execRequire:this.formData1.form.execRequire,
              execStreetUnitId: this.formData1.form.execStreetUnitId.join(","),
              execStreetUnit: streetNameTemp.join(","),
            }
            if(this.openType == "add"){
              this.add(tempParam)
            }else{
              this.update(tempParam)
            }
          })
        })
      },
      add(tempParam){
        tempParam.id = null
        patrolPlanDistributeAdd(tempParam).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      update(tempParam){
        patrolPlanDistributeUpdate(tempParam).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      cancel(){
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$refs.vformComponents1.$refs.form.resetFields();
        this.$emit('success')
      },
      close(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$refs.vformComponents1.$refs.form.resetFields();
        this.$emit('close')
      },
      getUnitListData(searchUnitId){
        // 默认查询当前人员单位
        let deptId = this.$store.state.account.user.deptId;
        if(searchUnitId){
           deptId = searchUnitId
        }
        // getInstitutionList({unitId: deptId}).then(res=>{
        //   if (res.code == 200) {
        //     this.belongUnitIdList = res.data.map(t => {return {id: t.unitId, name: t.unitName}})
        //   }
        // })

        getDeptList({deptId: deptId}).then(res=>{
          if(res.code==200){
            this.belongUnitIdList = res.data.map(t=>{ return {id:t.deptId, name:t.deptName} })
          }
        })

      },
      getStreetUnitListData(deptId){
        // 查询下级单位
        // let deptId = this.$store.state.account.user.deptId
        // getInstitutionList({fatherUnitId: deptId}).then(res=>{
        //     if(res.code==200){
        //       this.belongStreetUnitIdList = res.data.map(t=>{ return {id:t.unitId, name:t.unitName} })
        //     }
        // })
        getDeptList({deptId: deptId}).then(res=>{
          if(res.code==200){
            this.belongStreetUnitIdList = res.data.map(t=>{ return {id:t.deptId, name:t.deptName} })
          }
        })

      },
      getBuildingList() {
        collectBuildingProjectList().then(res => {
          if (res.code == 200) {
            this.buildingOptions = res.data
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      getData(){
        this.planCycleOptions = []
        this.$commonJs.filterDataDict("patrolPlanCycle",this.planCycleOptions)
        this.getUnitListData()
        this.getBuildingList();
        // this.getStreetUnitListData()
        if(this.openType!="add"){
          patrolPlanDistributeDetail(this.id).then(res=>{
            if(res.code==200){
              this.formData.form = res.data
              this.formData1.form.execStreetUnitId = res.data.execStreetUnitId != null ? res.data.execStreetUnitId.split(",") : []
              this.formData1.form.execRequire = res.data.execRequire
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }
      }
    },
  };
</script>

<style lang="scss" scoped>
  @import "@/styles/element-variables.scss";
  .formTitle-root{
    padding: 10px 0;
    border-bottom: 1px solid #EFEFEF;
    font-size: 16px;
    position: relative;
    margin-bottom: 10px;
    .form-title-p{
      padding-left: 10px;
      border-left: 4px solid $--color-primary;
    }
  }
</style>
